package com.study.file.controller;

import com.study.common.entity.LoginException;
import com.study.common.entity.ResultInfo;
import com.study.common.enumerate.ExceptionInfo;
import com.study.common.utils.ResultUtils;
import com.study.file.service.DownloadService;
import com.study.file.service.SaveService;
import com.study.main.vo.ConditionPagination;
import org.apache.commons.io.FileUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.security.NoSuchAlgorithmException;

/**
 * @Author 谭永超 [www.tanyongchao.tk:8090/SumDome/index]
 * @Date 2018/9/10 14:14
 * @Description 对excel 的读写
 */
@Controller
@RequestMapping(value = "/file")
public class FileController {
    @Autowired
    @Qualifier(value = "saveService")
    private SaveService saveService;
    @Autowired
    @Qualifier(value = "downloadService")
    private DownloadService downloadService;

    private static String name;

    @RequiresPermissions(value = "all")
    @RequestMapping(value = "/upload", method = {RequestMethod.POST})
    @ResponseBody
    public ResultInfo upload(@RequestParam("file") MultipartFile file, ModelMap modelMap) throws NoSuchAlgorithmException {
        System.out.println("进入");
        ResultUtils resultUtils = new ResultUtils();
        if (!file.isEmpty()) {
            try {
                // 这里只是简单例子，文件直接输出到项目路径下。
                // 实际项目中，文件需要输出到指定位置，需要在增加代码处理。
                // 还有关于文件格式限制、文件大小限制，详见：中配置。
                name = file.getOriginalFilename();
                BufferedOutputStream out = new BufferedOutputStream(
                        new FileOutputStream(new File(System.getProperty("user.dir") + "/" + file.getOriginalFilename())));
                out.write(file.getBytes());
                out.flush();
                out.close();
                saveService.saveMyDate(name);
                modelMap.addAttribute("name", name);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                return resultUtils.fail("导入数据失败");
            } catch (IOException e) {
                e.printStackTrace();
                return resultUtils.fail("导入数据失败");
            }
            return resultUtils.success(null, "导入数据成功");
        } else {
            return resultUtils.fail("上传失败,文件是空的");
        }
    }

    /**
     * 导出数据
     *
     * @return com.study.common.entity.ResultInfo
     */
    @RequiresPermissions(value = "all")
    @RequestMapping(value = "/download", method = {RequestMethod.POST})
    public ResultInfo download(@ModelAttribute ConditionPagination conditionPagination,Model model, HttpServletResponse res, HttpServletRequest request) {
        try {
            String url = "/Users/apple/IdeaProjects/workAttendanceLog";
            String filename = downloadService.download(url,conditionPagination);
            String path = url;
            File file = new File(url+"/"+filename);
            OutputStream os = res.getOutputStream();
            try {
                res.reset();
                res.setHeader("Content-Disposition", "attachment; filename="+filename);
                res.setContentType("application/octet-stream; charset=utf-8");
                os.write(FileUtils.readFileToByteArray(file));
                os.flush();
            } finally {
                if (os != null) {
                    os.close();
                }
            }
       return new ResultUtils().success(null,null);
        } catch (Exception e) {
           throw new LoginException(ExceptionInfo.FORMAT_ERROR);
        }
    }
    /**
     *  根据选择导出数据
     *
     * @return com.study.common.entity.ResultInfo
     */
    @RequiresPermissions(value = "all")
    @RequestMapping(value = "downloadOne", method = {RequestMethod.POST})
    @ResponseBody
    public ResultInfo downloadOne(@ModelAttribute ConditionPagination conditionPagination, Model model, HttpServletResponse res, HttpServletRequest request) {
        try {
            String url = "/Users/apple/IdeaProjects/workAttendanceLog";
            String filename = downloadService.download(url,conditionPagination);
            String path = url;
            File file = new File(url+"/"+filename);
            OutputStream os = res.getOutputStream();
            try {
                res.reset();
                res.setHeader("Content-Disposition", "attachment; filename="+filename);
                res.setContentType("application/octet-stream; charset=utf-8");
                os.write(FileUtils.readFileToByteArray(file));
                os.flush();
            } finally {
                if (os != null) {
                    os.close();
                }
            }
            return new ResultUtils().success(null,null);
        } catch (Exception e) {
            throw new LoginException(ExceptionInfo.FORMAT_ERROR);
        }
    }
}
